
#include <nds.h>
#include <stdio.h>
#include "drunkenlogo.h"

//------------------------Keyboard Functions---------------------------------
void OnKeyPressed(int key) {
   if(key > 0)
      iprintf("%c", key);
}

//-------------------------Display Functions---------------------------------
SpriteEntry OAMCopy[128];

void initOAM(void) {
	int i;

	for(i = 0; i < 128; i++) {
		OAMCopy[i].attribute[0] = ATTR0_DISABLED;
	}	
}

void updateOAM(void) {	
	memcpy(OAM, OAMCopy, 128 * sizeof(SpriteEntry));
}

//----------------------------------Main-------------------------------------

int main(void)  {   
    //255 191
    char myName[256];
	int min_x  = 4096 , min_y  = 4096, max_x  = 0, max_y   = 0;
	int min_px = 4096 , min_py = 4096, max_px = 0 , max_py = 0;
	touchPosition touch;    
    
	//Init video
    videoSetMode(MODE_5_2D);
    videoSetModeSub(MODE_0_2D);
	vramSetBankA(VRAM_A_MAIN_BG);
    vramSetBankC(VRAM_C_SUB_BG);
    consoleDemoInit();
   
    PrintConsole topScreen = *consoleInit(0, 3,BgType_Bmp16 , BgSize_T_256x256, 31, 1, true);
	PrintConsole bottomScreen = *consoleInit(0, 3,BgType_Text4bpp, BgSize_T_256x256, 31, 0, false);
    
    consoleSelect(&topScreen);
    int id = bgInit(3, BgType_Bmp16, BgSize_B16_256x256, 0,0);
    initOAM();        
	decompress(drunkenlogoBitmap, BG_GFX,  LZ77Vram);

    consoleSelect(&bottomScreen);
    Keyboard *kbd = keyboardGetDefault();
    kbd->OnKeyPressed = OnKeyPressed;  
    //keyboardInit(kbd);
    //keyboardShow();

    while(1) {      
        //scanf("%s", myName);
        //while(!keysDown())scanKeys();
		
        iprintf("\x1b[6;5HTouch x = %04X, %04X\n", touch.rawx, touch.px);
		iprintf("\x1b[7;5HTouch y = %04X, %04X\n", touch.rawy, touch.py);		

		iprintf("\x1b[0;18Hkeys: %08X\n", keysHeld());
		//iprintf("\x1b[9;10HFrame %d\n", frame);
		
		iprintf("\x1b[12;12H(%d,%d)      ",touch.px,touch.py);

		if ( touch.rawx > max_x)		max_x = touch.rawx;
		if ( touch.rawy > max_y)		max_y = touch.rawy;
		if ( touch.px > max_px)	max_px = touch.px;
		if ( touch.py > max_py)	max_py = touch.py;

		if ( touch.rawx < min_x)		min_x = touch.rawx;
		if ( touch.rawy < min_y)		min_y = touch.rawy;
		if ( touch.px < min_px)	min_px = touch.px;
		if ( touch.py < min_py)	min_py = touch.py;

		iprintf("\x1b[0;0H(%d,%d)      ",min_px,min_py);
		iprintf("\x1b[1;0H(%d,%d)      ",min_x,min_y);
		iprintf("\x1b[22;21H(%d,%d)",max_x,max_y);
		iprintf("\x1b[23;23H(%d,%d)",max_px,max_py);

        
        //Update
        swiWaitForVBlank();
        updateOAM();
        keyboardUpdate();
        scanKeys();
        touchRead(&touch);
        //consoleClear();
    }

   return 0;
}
